package com.bac.bacplatform;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import com.bac.utils.Storage;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

public class BacApplication extends Application {
	public static final String TAG = "VolleyPatterns";
	private static final String SET_COOKIE_KEY = "Set-Cookie";//"JSESSIONID";
	private static final String COOKIE_KEY = "Cookie";
	private static final String SESSION_COOKIE = "JSESSIONID";
	/**
	 * 全局request
	 */
	private RequestQueue mRequestQueue;

	/**
	 * 静态实例，实现单例
	 */
	private static BacApplication mInstance;
	
	
	/**
	 * 全局数组，管理所有activity实例
	 */
	private List<Activity> activityList = new LinkedList<Activity>();

	@Override
	public void onCreate() {
		super.onCreate();
		
		SDKInitializer.initialize(this);
		
		mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		mInstance = this;
		
		// 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				// .memoryCacheExtraOptions(480, 800) // max width, max
				// height，即保存的每个缓存文件的最大长宽
				// .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
				// null) // Can slow ImageLoader, use it carefully (Better don't
				// use it)设置缓存的详细信息，最好不要设置这个
				.threadPoolSize(5)
				// 线程池内加载的数量
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				// .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
				// 1024)) // You can pass your own memory cache
				// implementation你可以通过自己的内存缓存实现
				// .memoryCacheSize(2 * 1024 * 1024)
				// /.discCacheSize(50 * 1024 * 1024)
				.discCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
																		// 加密
				// .discCacheFileNameGenerator(new
				// HashCodeFileNameGenerator())//将保存的时候的URI名称用HASHCODE加密
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// .discCacheFileCount(100) //缓存的File数量
				 .discCache(new UnlimitedDiscCache(StorageUtils.getOwnCacheDirectory(getApplicationContext(), "imageloader/Cache")))//自定义缓存路径
				// .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				// .imageDownloader(new BaseImageDownloader(context, 5 * 1000,
				// 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);// 全局初始化此配置
	}

	/**
	 * @return 返回单例的application
	 */
	public static synchronized BacApplication getInstance() {
		if (null == mInstance) {
			mInstance = new BacApplication();
		}
		return mInstance;
	}

	/**
	 * 将启动的activity放到全局数组里面
	 * @param activity 当前启动的activity实例
	 */
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	/**
	 * 关闭所有activity，彻底退出程序
	 */
	public void exit() {
		for (Activity activity : activityList) {
			activity.finish();
		}
		System.exit(0);
	}
	
	public RequestQueue getRequestQueue() {
		// lazy initialize the request queue, the queue instance will be
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}

		return mRequestQueue;
	}

	public <T> void addToRequestQueue(Request<T> req, String tag) {
		// set the default tag if tag is empty
		req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

		VolleyLog.d("Adding request to queue: %s", req.getUrl());

		getRequestQueue().add(req);
	}

	public <T> void addToRequestQueue(Request<T> req) {
		// set the default tag if tag is empty
		req.setTag(TAG);

		getRequestQueue().add(req);
	}

	/**
	 * 停止对应tag的request
	 * @param tag标注request
	 */
	public void cancelPendingRequests(Object tag) {
		if (mRequestQueue != null) {
			mRequestQueue.cancelAll(tag);
		}
	}
	
	/**
     * Checks the response headers for session cookie and saves it
     * if it finds it.
     * @param headers Response Headers.
     */
    public final void checkSessionCookie(Map<String, String> headers) {
        if (headers.containsKey(SET_COOKIE_KEY) && headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
        	Log.i(TAG+"-----headers", headers.toString());
        	Log.i(TAG+"------cookie", headers.get(SET_COOKIE_KEY));
                String cookie = headers.get(SET_COOKIE_KEY);
                if (cookie.length() > 0) {
                	String[] splitCookie = cookie.split(";");
                    String[] splitSessionId = splitCookie[0].split("=");
                    cookie = splitSessionId[1];
                	Storage.saveString(getApplicationContext(), SESSION_COOKIE, cookie);
                	Log.i(TAG+"----jsessionid", cookie);
                }
            }
    }

    /**
     * Adds session cookie to headers if exists.
     * @param headers
     */
    public final void addSessionCookie(Map<String, String> headers) {
        String sessionId = Storage.getString(getApplicationContext(), SESSION_COOKIE);
        if (sessionId.length() > 0) {
        	StringBuilder builder = new StringBuilder();
            builder.append(SESSION_COOKIE);
            builder.append("=");
            builder.append(sessionId);
            if (headers.containsKey(COOKIE_KEY)) {
                builder.append("; ");
                builder.append(headers.get(COOKIE_KEY));
            }
            Log.i(TAG+"----locale session", builder.toString());
            headers.put(COOKIE_KEY, builder.toString());
        }
    }

}
